package edu.tjut.tjutcommunity.controller;


import edu.tjut.tjutcommunity.entity.*;
import edu.tjut.tjutcommunity.service.PostService;
import edu.tjut.tjutcommunity.service.PostlogsService;
import edu.tjut.tjutcommunity.service.StarService;
import edu.tjut.tjutcommunity.service.UserService;
import edu.tjut.tjutcommunity.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yhh
 * @since 2022-05-01
 */
@RestController
public class StarController {

    final
    UserService userService;
    final
    StarService starService;
    final
    PostService postService;
    final
    PostlogsService postlogsService;


    public StarController(StarService starService, UserService userService, PostService postService, PostlogsService postlogsService) {
        this.starService = starService;
        this.userService = userService;
        this.postService = postService;
        this.postlogsService = postlogsService;
    }

    @GetMapping("/star/{pid}")
    public Message star(@PathVariable Integer pid) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        if (starService.star(user.getUid(), pid)) {
            postlogsService.insert(user, pid, 2);
            return Message.ok(new Pair<>("msg", "收藏成功"));
        }
        ;
        return Message.failed("已收藏");
    }

    @GetMapping("/unstar/{pid}")
    public Message unstar(@PathVariable Integer pid) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        if (starService.unstar(user.getUid(), pid)) {
            postlogsService.delete(user, pid,2);
            return Message.ok();
        }

        return Message.failed("取消收藏失败");
    }

    @PostMapping("/myCollect")
    public Message myStar(@RequestParam("pageNo") Integer pageNo, @RequestParam(value = "keyword", required = false) String keyword) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        PageResult<Post> starResult = starService.myStar(user.getUid(), pageNo, keyword);
        if (starResult.getResult().isEmpty()) {
            return Message.empty();
        }
        //访问根据pid获得
        return Message.ok(starResult);
    }

    /**
     * 判断该贴子是否已收藏
     * @param pid
     * @return
     */
    @GetMapping("/isstar/{pid}")
    public Message isStar(@PathVariable String pid) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        if (user != null) {
            //如果是从推荐来的，需要将recommend的feedback置为已浏览。
            postlogsService.insert(user, Integer.valueOf(pid), 0);
        }
        if (starService.isStar(user.getUid(), pid)) {
            return Message.HasStar();
        }
        return Message.NoStar();
    }
}

